<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f4f4f4;
        }

        h1 {
            color: #333;
            text-align: center;
        }

        ul {
            list-style-type: none;
            padding: 0;
        }

        li {
            background: #fff;
            margin: 10px 0;
            padding: 10px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        table {
            width: 100%;
            border-collapse: collapse;
            /* 合并边框 */
            margin-top: 10px;
            /* 表格上方间距 */
        }

        th,
        td {
            padding: 12px;
            /* 内边距 */
            text-align: left;
            /* 左对齐 */
            border-bottom: 1px solid #ddd;
            /* 底部边框 */
        }

        th {
            background-color: #f2f2f2;
            /* 表头背景色 */
            color: #333;
            /* 表头文字颜色 */
        }

        tr:hover {
            background-color: #f5f5f5;
            /* 鼠标悬停行的背景色 */
        }

        th,
        td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
            border-right: 1px solid #ddd;
            /* 添加右边框 */
        }

        th:last-child,
        td:last-child {
            border-right: none;
            /* 最后一列不显示右边框 */
        }
    </style>
</head>

<body>
    <!-- Start Generation Here -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
    <div id="app">
        <h3>
            SQL 展示
            <label for=""><input type="checkbox" v-model="showSetShow">排除set/show语句</label>
        </h3>
        <ul>
            <li v-for="sqlObj,i in sqls" :key="sqlObj.sql">
                <div style="color: gray;">
                    {{ sqlObj.datetime }}
                    <button @click="copyToClipboard(i, sqlObj.sql)">复制</button> <!-- 复制按钮 -->
                    <button @click="showResult(sqlObj.id)">查看结果</button>
                    <span v-if="currentPos == i && copyFeedback" style="color: green; margin-left: 10px;">{{
                        copyFeedback }}</span> <!-- 显示反馈信息 -->
                </div> <!-- 显示时间 -->
                <div>{{ sqlObj.sql }}</div>
                <div v-if="sqlObj.id == resultId" style="overflow-x: auto;">
                    <table v-if="result.columns && result.columns.length > 0">
                        <thead>
                            <tr>
                                <th v-for="field in result.columns" :key="field.OrgName">{{ field.OrgName }}</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="rows,i in result.rows" :key="i">
                                <td v-for="row,ii in rows" :key="ii">{{ row }}</td>
                            </tr>
                        </tbody>

                    </table>
                    <div v-else>
                        <table>
                            <thead>
                                <th>受影响的行数</th>
                                <th>最后插入的ID</th>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>{{result.affected_rows}}</td>
                                    <td>{{result.last_insert_id}}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </li>
        </ul>

    </div>

    <script>
        function uuid(){
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }
        var closeCopyTimer

        var fetchTimer

        new Vue({
            el: '#app',
            data: {
                sqls: [],
                copyFeedback: '', // 新增反馈状态
                currentPos: -1,
                showSetShow: true,
                resultId: "",
                result: null,
                requestId: ""
            },
            watch: {
                showSetShow: function (newVal, oldVal) {
                    this.sqls = []
                    this.fetchSQLs()
                }
            },
            mounted() {
                this.fetchSQLs();
            },
            methods: {
                fetchSQLs() {
                    var requestId = uuid()
                    this.requestId = requestId
                    var id = this.sqls?.length > 0 ? this.sqls[0].id : ""
                    fetch('/data?id=' + id)
                        .then(response => response.json())
                        .then(data => {
                            if (this.requestId != requestId) {
                                return
                            }
                            var sqls = data.sqls?.filter(item => {
                                if (!this.showSetShow) {
                                    return true
                                }
                                if (item.sql.startsWith('set') || item.sql.startsWith('show') || item.sql.startsWith('SET') || item.sql.startsWith('SHOW')) {
                                    return false
                                }
                                return true
                            }); // 更新sqls
                            if(sqls){
                                this.sqls.unshift(...sqls);
                                if (this.sqls.length > 100) {
                                    this.sqls = this.sqls.slice(0, 100); // 保留前100个
                                }
                                // this.sqls = this.sqls.concat(sqls)
                            }
                        })
                        .catch(error => console.error('获取SQL时出错:', error))
                        .finally(() => {
                            clearTimeout(fetchTimer)
                            fetchTimer = setTimeout(() => this.fetchSQLs(), 500); // 5秒后再次请求
                        });

                },
                formatDate(datetime) {

                    const date = new Date(datetime);
                    return date.toISOString().slice(0, 19).replace('T', ' '); // 转换为yyyy-MM-dd HH:mm:ss格式
                },
                copyToClipboard(i, sql) {
                    this.currentPos = i
                    this._copyToClipboard(sql)
                    this.copyFeedback = '复制成功'; // 设置反馈信息
                    clearTimeout(closeCopyTimer)
                    closeCopyTimer = setTimeout(() => this.copyFeedback = '', 2000); // 2秒后清除反馈
                },
                _copyToClipboard(text) {
                    const textarea = document.createElement('textarea');
                    textarea.value = text;
                    document.body.appendChild(textarea);
                    textarea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textarea);
                },

                showResult(id) {
                    if (this.resultId == id) {
                        this.resultId = ""
                        this.result = null
                    } else {
                        console.log(id)
                        fetch('/result?id=' + id).then(res => {
                            res.json().then(data => {
                                this.result = data.result
                                this.resultId = id
                            })
                            // console.log(res)
                        })
                    }
                }
            }
        });

    </script>
    <!-- End Generation Here -->
</body>

</html>